import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_module/base/model/constants.dart';
import 'package:flutter_module/base/util/sp_util.dart';
import 'package:flutter_module/controller/mine_controller.dart';
import 'package:flutter_module/pages/root_page/skeleton_item.dart';
import 'package:flutter_module/router/routers.dart';
import 'package:flutter_module/util/app_colors.dart';
import 'package:flutter_module/widget/custom_refresher.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

//列表
//下载刷新、加载更多 + getx实现
class MinePage extends StatefulWidget {
  final Map<dynamic, dynamic> params;

  ///获取native层传递过来的信息

  const MinePage({super.key, required this.params});

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  final _controller = Get.find<MineController>();

  /// 刷新数据插件的控制器
  late RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    SharedPreferencesU.preInit();
    var cookie = widget.params[Constants.cookie];
    Logger.log('initState, ${widget.params[Constants.cookie]}');
    //保存cookie，执行网络请求
    SharedPreferencesU.getInstance().setData(Constants.cookie, cookie);
    // print("initState 1");//登录之后，该方法就被触发了，优化处理，进行懒加载

    // 创建刷新数据插件的控制器
    _refreshController = RefreshController();
    _controller.onRefresh();
  }

  // @override
  // void dispose() {
  //   super.dispose();
  //   _refreshController.dispose();
  // }

  void _loadData() async {
    await Future.delayed(const Duration(seconds: 1), () {
      _controller.onRefresh();
      // 获取网络数据成功时:刷新结束
      _refreshController.refreshCompleted();
    });
  }

  void _loadMore() async {
    await Future.delayed(const Duration(seconds: 1), () async {
      _controller.loadMore();
      _refreshController.loadComplete();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("收藏列表"),
      ),

      /// GetX改造步骤3：使用GetBuilder进行包裹
      ///参考  https://juejin.cn/post/7064483004038512648
      ///GetBuilder  是一个 Widget 组件， 在 GetX 的状态管理中，GetBuilder  的主要作用是结合 GetxController  实现界面数据的更新。当调用 GetxController 的 update 方法时，GetBuilder  包裹的 Widget 就会刷新从而实现界面数据的更新。
      body: GetBuilder<MineController>(builder: (controller) {
        return CustomRefresher(
          controller: _refreshController,
          enablePullUp: true,
          onRefresh: _loadData,
          onLoading: _loadMore,
          child: buildCustomScrollView(),
        );

        // return EasyRefresh(
        //   // controller: _easyRefreshController,//存在一些问题，暂不使用easy_refresh
        //   //定义类似PhoenixHeader和PhoenixFooter，需要手动下载才能加载更多或者以其它的方式进行设置（暂未研究）
        //   //暂时使用默认的  使用默认的会存在一个问题，底部的加载条目存在错位。
        //   // header: const PhoenixHeader(),
        //   // footer: const PhoenixFooter(),
        //   onRefresh: () async {
        //     await Future.delayed(const Duration(seconds: 1), () {
        //       controller.onRefresh();
        //       // _easyRefreshController.finishRefresh();
        //       // _easyRefreshController.resetFooter();
        //     });
        //   },
        //   onLoad: () async {
        //     await Future.delayed(const Duration(seconds: 1), () async {
        //       controller.loadMore();
        //       // _easyRefreshController.finishLoad(IndicatorResult.success);
        //       // _easyRefreshController.finishLoad(IndicatorResult.noMore);
        //       // _easyRefreshController.resetFooter();
        //     });
        //   },
        //   // child: buildCustomScrollView(),
        //   child: buildCustomScrollView(),
        // );
      }),
    );
  }

  ///参考   --->   https://book.flutterchina.club/chapter6/custom_scrollview.html#_6-10-1-customscrollview
  CustomScrollView buildCustomScrollView() {
    // SliverFixedExtentList 是一个 Sliver，它可以生成高度相同的列表项。
    // 再次提醒，如果列表项高度相同，我们应该优先使用SliverFixedExtentList
    // 和 SliverPrototypeExtentList，如果不同，使用 SliverList.
    // var listView = SliverFixedExtentList(
    //   itemExtent: 56, //列表项高度固定
    //   delegate: SliverChildBuilderDelegate(
    //     (_, index) => ListTile(title: Text('$index')),
    //     childCount: 10,
    //   ),
    // );
    return CustomScrollView(
      slivers: [
        SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
            return GestureDetector(
              onTap: () => openH5Detail(index),
              // onTap: openH5Detail(index),//错误写法，会导致openH5Detail方法没有被点击就执行了
              child: buildItem(index),
            );
            return const SkeletonItem();
          }, childCount: _controller.articleListInfo.length),
          // }, childCount: _count),
        ),
      ],
    );
  }

  openH5Detail(int index) {
    var article = _controller.articleListInfo[index];

    ///flutter页面跳转flutter页面
    // Get.toNamed(RouteGet.web, arguments: {Constants.url: article.link});
    // BoostNavigator.instance.push(RouteGet.web, arguments: {Constants.url: article.link});
    BoostNavigator.instance.push(RouteGet.navigationPage); //测试
  }

  Widget buildItem(int index) {
    var article = _controller.articleListInfo[index];

    print("article ------> $article");

    if (article.envelopePic.isEmpty) {
      return Container(
        margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        decoration: BoxDecoration(boxShadow: [
          //卡片阴影
          BoxShadow(
            color: Colors.white,
            // offset: Offset(0, 0),
            blurRadius: 5,
          )
        ]),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Flex(
              direction: Axis.horizontal,
              children: [
                Text("新",
                    style:
                        TextStyle(fontSize: 14, color: AppColors.color_6c1bc)),
                Expanded(
                    flex: 1,
                    child: Text(article.chapterName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14, color: AppColors.color_7c7b7b))),
                Text(article.niceDate,
                    style:
                        TextStyle(fontSize: 12, color: AppColors.color_999999))
              ],
            ),
            Text(article.title,
                textAlign: TextAlign.left,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 14, color: AppColors.color_000000)),
            Flex(
              direction: Axis.horizontal,
              children: [
                Expanded(
                    flex: 1,
                    child: Text(article.author,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 12, color: AppColors.color_999999))),
                Image.asset(
                  "assets/images/icon_collected.png",
                  width: 16,
                ),
              ],
            )
          ],
        ),
      );
      //样式1
      // return Container(
      //   margin: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
      //   padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
      //   decoration: BoxDecoration(boxShadow: [
      //     //卡片阴影
      //     BoxShadow(
      //       color: Colors.white,
      //       // offset: Offset(0, 0),
      //       blurRadius: 5.sp,
      //     )
      //   ]),
      //   child: Column(
      //     crossAxisAlignment: CrossAxisAlignment.start,
      //     children: [
      //       Flex(
      //         direction: Axis.horizontal,
      //         children: [
      //           Text("新",
      //               style: TextStyle(
      //                   fontSize: 14.sp, color: AppColors.color_6c1bc)),
      //           Expanded(
      //               flex: 1,
      //               child: Text(article.chapterName,
      //                   maxLines: 1,
      //                   overflow: TextOverflow.ellipsis,
      //                   style: TextStyle(
      //                       fontSize: 14.sp, color: AppColors.color_7c7b7b))),
      //           Text(article.niceDate,
      //               style: TextStyle(
      //                   fontSize: 12.sp, color: AppColors.color_999999))
      //         ],
      //       ),
      //       Text(article.title,
      //           textAlign: TextAlign.left,
      //           maxLines: 2,
      //           overflow: TextOverflow.ellipsis,
      //           style:
      //               TextStyle(fontSize: 14.sp, color: AppColors.color_000000)),
      //       Flex(
      //         direction: Axis.horizontal,
      //         children: [
      //           Expanded(
      //               flex: 1,
      //               child: Text(article.author,
      //                   maxLines: 1,
      //                   overflow: TextOverflow.ellipsis,
      //                   style: TextStyle(
      //                       fontSize: 12.sp, color: AppColors.color_999999))),
      //           Image.asset(
      //             "assets/images/icon_collected.png",
      //             width: 16,
      //           )
      //         ],
      //       )
      //     ],
      //   ),
      // );
    } else {
      return Container(
        margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        decoration: BoxDecoration(boxShadow: [
          //卡片阴影
          BoxShadow(
            color: Colors.white,
            // offset: Offset(0, 0),
            blurRadius: 5,
          )
        ]),
        child: Flex(
          direction: Axis.horizontal,
          children: [
            // _buildImageWidget(article.envelopePic),
            _buildImageWidget(
                "https://wbedu.sanyaedu.org/res/20240904/png/1ddad595-9094-4c74-9a20-e37ccfbb691d.png"),
            Expanded(
                flex: 1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Flex(
                      direction: Axis.horizontal,
                      children: [
                        Text("新",
                            style: TextStyle(
                                fontSize: 14, color: AppColors.color_6c1bc)),
                        Expanded(
                            flex: 1,
                            child: Text(article.chapterName,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 14,
                                    color: AppColors.color_7c7b7b))),
                        Text(article.niceDate,
                            style: TextStyle(
                                fontSize: 12, color: AppColors.color_999999))
                      ],
                    ),
                    Text(article.title,
                        textAlign: TextAlign.left,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14, color: AppColors.color_000000)),
                    Flex(
                      direction: Axis.horizontal,
                      children: [
                        Expanded(
                            flex: 1,
                            child: Text(article.author,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.color_999999))),
                        Image.asset(
                          "assets/images/icon_collected.png",
                          width: 16,
                        )
                      ],
                    )
                  ],
                ))
          ],
        ),
      );
      //样式2
      // return Container(
      //   margin: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
      //   padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
      //   decoration: BoxDecoration(boxShadow: [
      //     //卡片阴影
      //     BoxShadow(
      //       color: Colors.white,
      //       // offset: Offset(0, 0),
      //       blurRadius: 5.sp,
      //     )
      //   ]),
      //   child: Flex(
      //     direction: Axis.horizontal,
      //     children: [
      //       // _buildImageWidget(article.envelopePic),
      //       _buildImageWidget(
      //           "https://wbedu.sanyaedu.org/res/20240904/png/1ddad595-9094-4c74-9a20-e37ccfbb691d.png"),
      //       Expanded(
      //           flex: 1,
      //           child: Column(
      //             crossAxisAlignment: CrossAxisAlignment.start,
      //             children: [
      //               Flex(
      //                 direction: Axis.horizontal,
      //                 children: [
      //                   Text("新",
      //                       style: TextStyle(
      //                           fontSize: 14.sp, color: AppColors.color_6c1bc)),
      //                   Expanded(
      //                       flex: 1,
      //                       child: Text(article.chapterName,
      //                           maxLines: 1,
      //                           overflow: TextOverflow.ellipsis,
      //                           style: TextStyle(
      //                               fontSize: 14.sp,
      //                               color: AppColors.color_7c7b7b))),
      //                   Text(article.niceDate,
      //                       style: TextStyle(
      //                           fontSize: 12.sp, color: AppColors.color_999999))
      //                 ],
      //               ),
      //               Text(article.title,
      //                   textAlign: TextAlign.left,
      //                   maxLines: 2,
      //                   overflow: TextOverflow.ellipsis,
      //                   style: TextStyle(
      //                       fontSize: 14.sp, color: AppColors.color_000000)),
      //               Flex(
      //                 direction: Axis.horizontal,
      //                 children: [
      //                   Expanded(
      //                       flex: 1,
      //                       child: Text(article.author,
      //                           maxLines: 1,
      //                           overflow: TextOverflow.ellipsis,
      //                           style: TextStyle(
      //                               fontSize: 12.sp,
      //                               color: AppColors.color_999999))),
      //                   Image.asset(
      //                     "assets/images/icon_collected.png",
      //                     width: 16.w,
      //                   )
      //                 ],
      //               )
      //             ],
      //           ))
      //     ],
      //   ),
      // );
    }
  }

  Widget _buildImageWidget(url) {
    return Image.network(
      url,
      height: 120.h,
      width: 75.w,
    );
  }
}
